package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class SaveOrderStrategyContext implements ApplicationContextAware {

    // 定义一个Map类型的成员变量，存储策略实现类的对象
    private static final Map<String , SaveOrderStrategy> STRATEGY_MAP = new ConcurrentHashMap<>();

    public static final SaveOrderStrategy getSaveOrderStrategy(String payWay) {
        return STRATEGY_MAP.get(payWay) ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(SaveOrderStrategy.class).values().forEach(saveOrderStrategy -> {
            String payWay = saveOrderStrategy.getPayWay();
            STRATEGY_MAP.put(payWay , saveOrderStrategy) ;
        });
    }
}
